import * as vscode from 'vscode';

export class MyInlineCompletionProvider
  implements vscode.InlineCompletionItemProvider
{
  async provideInlineCompletionItems(
    document: vscode.TextDocument,
    position: vscode.Position,
    _context: vscode.InlineCompletionContext,
    _token: vscode.CancellationToken
  ): Promise<vscode.InlineCompletionItem[]> {
    //获取当前行到光标处的文本内容
    const currentLineText = document.lineAt(position).text.substring(0, position.character);
    // 仅当当前行为空或只包含空白，并且有上一行时触发
    if (position.line > 0 && currentLineText.trim() === '') {
      const prevLineText = document.lineAt(position.line - 1).text.trim();
      if (prevLineText.startsWith('//')) {
     
        try {
        /**
         * 1.调用注册的 内联代码提示命令 cw-vscode-ai.inlineCompletionRequest
         * 2.将上一行的注释内容发送到语言服务器
         * 3.使用语言服务器返回的结果作为内联补全建议
         * 4.返回内联补全建议
         */
          const response = await vscode.commands.executeCommand<string>(
            'cw-vscode-ai.inlineCompletionRequest',
            prevLineText // 将上一行的注释内容发送到语言服务器
          );

          // 使用语言服务器返回的结果作为内联补全建议
          if (response) {
            console.log('response::需要内联显示的位置: ', response);
            return [
              new vscode.InlineCompletionItem(
                response,
                new vscode.Range(position, position)
              ),
            ];
          }
        } catch (error) {
          console.error('获取内联补全结果失败:', error);
        }
      }
    }
    return [];
  }
}

export function registerMyInlineCompletion(context: vscode.ExtensionContext) {
  const provider = vscode.languages.registerInlineCompletionItemProvider(
    { pattern: '**/*.{js,ts,html,css}' },
    new MyInlineCompletionProvider()
  );
  context.subscriptions.push(provider);
}
